// pages/order/list.js
import {
    ORDER_STATES,
    ORDER_STATES_WZF,
    ORDER_STATES_NOBTN,
    ORDER_STATES_YZF,
    ORDER_STATES_DDYWC
} from './constant'
import {
    getOrders,
    getPayment,
    addOrder,
    changeOrderStatus
} from '../../utils/apis'

import {
    alert,
    datetimeFormat,
    requestPayment,
    getCurrentPage,
    confirm
} from '../../utils/util'

var initData = {
    page: 0,
    size: 10,
    hasMore: true,
    loading: false,
    list: []
}

const app = getApp()

Page({
    data: {
        ORDER_STATES,
        ORDER_STATES_WZF,
        ORDER_STATES_YZF,
        ORDER_STATES_DDYWC,
        currentType: 0,
        list: null,
        url: '/images/default-image.png',
        first: true
    },
    onLoad: function(options) {
        // 页面初始化 options为页面跳转所带来的参数
    },
    onShow: function() {
        // 页面显示
        var that = this
        app.getLoginInfo(loginInfo => {
            if (loginInfo.token) {
                that.initData()
                that.setData({
                    loginInfo: loginInfo
                })
            }
        })
    },
    onHide: function() {
        // 页面隐藏
    },
    onUnload: function() {
        // 页面关闭
    },
    initData(cb) {
        this.setData(initData)
        this.loadData(cb)
    },
    loadData(cb) {
        var that = this
        var { loading, page, size, currentType } = this.data
        if (loading) {
            return
        }

        this.setData({
            loading: true
        })
        getOrders({
            page,
            size,
            currentType
        }).then(data => {
            console.log(data)
            // result: {order,orderDetailList}
            var { list } = that.data
            var { result, next, total, totalPage } = data

            result.map(v => {
                const bizStatus = v.order.bizStatus

                if (ORDER_STATES_WZF.indexOf(bizStatus) != -1) {
                    v.t = 'ORDER_STATES_WZF'
                } else if (ORDER_STATES_YZF.indexOf(bizStatus) != -1) {
                    v.t = 'ORDER_STATES_YZF'
                } else if (ORDER_STATES_DDYWC.indexOf(bizStatus) != -1) {
                    v.t = 'ORDER_STATES_DDYWC'
                } else {
                    v.t = 'ORDER_STATES_NOBTN'
                }

                return v
            })

            that.setData({
                loading: false,
                list: list ? list.concat(result) : result,
                hasMore: total > (page + 1) * size,
                page: page + 1
            })
            if (that.data.list.length > 0) {
                that.setData({
                    first: true
                })
            } else {
                that.setData({
                    first: false
                })
            }
            cb && cb()
        })
    },
    //切换类型
    changeType(e) {
        let index = e.currentTarget.dataset.index
        this.setData({
            currentType: index
        })

        this.onPullDownRefresh()
    },
    goOrder(e) {
        let { id, status } = e.currentTarget.dataset
        console.log(id, status)
        wx.navigateTo({
            url: '/pages/order/show?id=' + id + '&status=' + status
        })
    },

    onReachBottom(e) {
        var {
            loginInfo: { token },
            hasMore,
            loading
        } = this.data
        if (token && hasMore && !loading) {
            this.loadData()
        }
    },
    onPullDownRefresh() {
        var {
            loginInfo: { token }
        } = this.data
        if (token != '') {
            wx.showNavigationBarLoading()
            this.initData(() => {
                wx.hideNavigationBarLoading()
                wx.stopPullDownRefresh()
            })
        } else {
            wx.stopPullDownRefresh()
        }
    },
    // 调用 onload
    load() {
        getCurrentPages()[getCurrentPages().length - 1].onLoad()
    },
    // 立即付款按钮
    onPayTap(e) {
        let order_index = e.currentTarget.dataset.index,
            { list } = this.data,
            { id, storeId } = list[order_index].order,
            that = this

        addOrder({
                // 去支付
                orderinfo: {
                    orderId: id,
                    storeId: storeId
                }
            })
            .then(data => {
                requestPayment({
                    data,
                    complete() {
                        that.setData({
                            loading: false
                        })
                        that.initData(() => {
                            wx.hideNavigationBarLoading()
                            wx.stopPullDownRefresh()
                        })
                    }
                })
            })
            .catch(_res => {
                if ((_res = 'requestPayment:fail cancel')) {
                    //手动取消
                } else {
                    //接口500
                }
                that.setData({
                    loading: false
                })
            })
    },
    asyncOrderStatus(id, bizstatus) {
        changeOrderStatus({
            id,
            bizstatus
        }).then(res => {
            let alert_text

            if (bizstatus != 17) {
                this.initData(() => {
                    wx.hideNavigationBarLoading()
                    wx.stopPullDownRefresh()
                })
            }

            switch (bizstatus) {
                case '2':
                    alert_text = '取消订单成功'
                    break
                case '19':
                    alert_text = '已为您申请退款'
                    break
                case '11':
                    alert_text = '确认收货成功'
                    break
                case '17':
                    alert_text = '已为您催单，请耐心等待'
                    break
                default:
                    break
            }

            return alert(alert_text)
        })
    },
    // 取消订单:2 申请退款:19 确认收货:11 催单:17
    changeOrderStatus(e) {
        let that = this
        let { id, bizstatus } = e.currentTarget.dataset
        console.log(id, bizstatus)
        app.getLoginInfo(loginInfo => {
            if (!loginInfo) {
                return alert('用户未登录')
            } else {
                let content = '',
                    flag = true

                switch (bizstatus) {
                    case '2':
                        content = '是否取消订单？'
                        break
                    case '19':
                        content = '是否申请退款？'
                        break
                    default:
                        flag = false
                        that.asyncOrderStatus(id, bizstatus)
                        break
                }

                if (flag) {
                    confirm({
                        content: content,
                        cancelText: '取消',
                        ok: function() {
                            that.asyncOrderStatus(id, bizstatus)
                        }
                    })
                }
            }
        })
    }
})